<template>
  <div class="upload-page">
    <el-row :gutter="30" class="equal-height-row">
      <!-- 左侧上传区域 (span=9) -->
      <el-col :span="9">
        <div class="upload-left">
          <!-- 视频上传区域 -->
          <div class="upload-section video-upload">
            <el-upload
                ref="videoUpload"
                class="upload-core"
                drag
                action="#"
                :limit="1"
                :file-list="videoFiles"
                :before-upload="beforeVideoUpload"
                :http-request="handleVideoUpload"
            >
              <div class="upload-content">
                <i class="el-icon-upload"></i>
                <div class="upload-text">拖拽视频文件到此处</div>
              </div>
            </el-upload>
            <el-button
                class="upload-trigger-btn"
                type="primary"
                plain
                @click="triggerVideoUpload"
            >
              <i class="el-icon-video-camera"></i>
              选择视频文件
            </el-button>
            <div class="upload-tip">支持 MP4/AVI/MOV 格式，最大2GB</div>
          </div>

          <!-- 封面上传区域 -->
          <div class="upload-section cover-upload">
            <el-upload
                ref="coverUpload"
                class="upload-core"
                drag
                action="#"
                :show-file-list="false"
                :before-upload="beforeCoverUpload"
                :http-request="handleCoverUpload"
            >
              <div class="cover-preview">
                <img
                    v-if="form.cover"
                    :src="form.cover"
                    class="cover-image"
                >
                <div v-else class="cover-placeholder">
                  <i class="el-icon-picture-outline"></i>
                  <div class="cover-tip">拖拽封面到此处</div>
                </div>
              </div>
            </el-upload>
            <el-button
                class="upload-trigger-btn"
                type="primary"
                plain
                @click="triggerCoverUpload"
            >
              <i class="el-icon-picture"></i>
              选择封面图片
            </el-button>
            <div class="upload-tip">建议尺寸 16:9，支持 JPG/PNG</div>
          </div>
        </div>
      </el-col>

      <!-- 右侧表单区域 (span=15) -->
      <el-col :span="15">
        <!-- 原有表单内容保持不变 -->
        <el-form
            ref="formRef"
            :model="form"
            :rules="rules"
            label-width="80px"
            label-position="top"
            class="info-form"
        >
          <!-- 标题 -->
          <el-form-item label="视频标题" prop="videoTitle">
            <el-input
                v-model="form.videoTitle"
                placeholder="请输入视频标题（5-50字）"
                clearable
            />
          </el-form-item>

          <!-- 分区选择 -->
          <el-form-item label="视频分区" prop="videoPartitionId">
            <el-select
                v-model="form.videoPartitionId"
                placeholder="请选择视频分区"
                clearable
                style="width: 100%"
            >
              <el-option
                  v-for="item in categories"
                  :key="item.partitionId"
                  :label="item.partitionName"
                  :value="item.partitionId"
              />
            </el-select>
          </el-form-item>

          <!-- 上架时间 -->
          <el-form-item label="上架时间" prop="videoPublishTime">
            <el-date-picker
                v-model="form.videoPublishTime"
                type="datetime"
                placeholder="选择日期时间"
                format="YYYY-MM-DD HH:mm:ss"
                value-format="YYYY-MM-DD HH:mm:ss"
                :disabled-date="disabledDate"
                style="width: 100%"
            />
          </el-form-item>

          <!-- 视频简介 -->
          <el-form-item label="视频简介" prop="description">
            <el-input
                v-model="form.videoIntroduction"
                type="textarea"
                :rows="4"
                placeholder="请输入视频简介（最多500字）"
                resize="none"
                show-word-limit
                maxlength="500"
            />
          </el-form-item>

          <!-- 视频标签 -->
          <el-form-item label="视频标签" prop="videoTag">
            <el-select
                v-model="form.videoTag"
                multiple
                filterable
                allow-create
                placeholder="输入标签后回车确认（最多5个）"
                style="width: 100%"
                default-first-option
                :reserve-keyword="false"
            >
              <el-option
                  v-for="tag in suggestedTags"
                  :key="tag.tagId"
                  :label="tag.tagName"
                  :value="tag.tagName"
              />
            </el-select>
          </el-form-item>

          <!-- 提交按钮 -->
          <el-form-item>
            <el-button
                type="primary"
                size="large"
                :loading="submitting"
                @click="submitForm"
                class="submit-btn"
            >
              立即投稿
            </el-button>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
// ...其他代码保持不变...
import {ref, reactive, onMounted} from 'vue'
import { ElMessage } from 'element-plus'
import {getPartitionList, getTagList, uploadVideo} from "@/api/api.js";
import http from "@/api/http.js";
import {uploadCoverUrl, uploadVideoUrl} from "@/constant/url.js";


// 表单数据
const form = reactive({
  videoUrl: null,
  videoCover: '',
  videoTitle: '',
  videoPartitionId: '',
  videoPublishTime: '',
  videoIntroduction: '',
  videoTag: []
})

// 表单验证规则
const rules = reactive({
  videoUrl: [{ required: true, message: '请上传视频文件', trigger: 'change' }],
  videoTitle: [
    { required: true, message: '请输入视频标题', trigger: 'blur' },
    { min: 5, max: 50, message: '长度在5到50个字符', trigger: 'blur' }
  ],
  videoPartitionId: [{ required: true, message: '请选择视频分区', trigger: 'change' }],
  videoPublishTime: [{ required: true, message: '请选择上架时间', trigger: 'change' }],
  videoTag: [
    { type: 'array', max: 5, message: '最多选择5个标签', trigger: 'change' }
  ]
})

// 上传相关状态
const videoFiles = ref([])
const videoProgress = ref(0)

// 上传处理
const beforeVideoUpload = (file) => {
  const validTypes = ['video/mp4', 'video/avi', 'video/quicktime']
  const isValidType = validTypes.includes(file.type)
  const isValidSize = file.size <= 2 * 1024 * 1024 * 1024 // 2GB

  if (!isValidType) {
    ElMessage.error('仅支持 MP4/AVI/MOV 格式视频!')
    return false
  }

  if (!isValidSize) {
    ElMessage.error('视频大小不能超过2GB!')
    return false
  }

  return true
}

// import axios from 'axios'
// 上传配置
// const uploadBaseURL = 'http://localhost:8080'
// const videoUploadURL = `${uploadBaseURL}/user/common/upload/video`
// const imageUploadURL = `${uploadBaseURL}/user/common/upload/image`


// // 模拟带进度条的上传
// const interval = setInterval(() => {
//   if (videoProgress.value < 100) {
//     videoProgress.value += 10
//   }
// }, 200)
//
// form.video = await mockUpload(file)
// clearInterval(interval)
// videoProgress.value = 0
const handleVideoUpload = async ({file,onProgress}) => {
  try {
    const formData = new FormData()
    formData.append('file', file)

    const { data } = await http.post(uploadVideoUrl, formData, {
      headers: {
        'Content-Type': 'multipart/form-data',
        'authentication': `${localStorage.getItem('token')}`
      },
      onUploadProgress: progressEvent => {
        const percent = Math.round(
            (progressEvent.loaded * 100) / progressEvent.total
        )
        videoProgress.value = percent
        console.log(videoProgress.value)
        onProgress({ percent: percent })
      }
    })

    console.log(data)
    form.videoUrl = data
    console.log(form)
    ElMessage.success('视频上传成功')
  } catch (err) {
    ElMessage.error('视频上传失败')
    console.error('Upload error:', err)
  }
}

  // const url = await mockUpload(file)
  // form.cover = URL.createObjectURL(file)
const handleCoverUpload = async ({ file,onProgress }) => {
  try {
    const formData = new FormData()
    formData.append('file', file)

    const { data } = await http.post(uploadCoverUrl, formData, {
      headers: {
        'Content-Type': 'multipart/form-data',
        'authentication': `${localStorage.getItem('token')}`
      },
      onUploadProgress: progressEvent => {
        const percent = Math.round(
            (progressEvent.loaded * 100) / progressEvent.total
        )
        videoProgress.value = percent
        console.log(videoProgress.value)
        onProgress({ percent: percent })
      }
    })

    console.log(data)
    form.videoCover = data
    console.log(form)
    ElMessage.success('封面上传成功')
  } catch (err) {
    ElMessage.error('封面上传失败')
    console.error('Upload error:', err)
  }
}

const beforeCoverUpload = (file) => {
  const isImage = ['image/jpeg', 'image/png'].includes(file.type)
  if (!isImage) {
    ElMessage.error('仅支持 JPG/PNG 格式图片!')
    return false
  }
  return true
}

// 其他数据
// const categories = ref([
//   { value: 'tech', label: '科技区' },
//   { value: 'life', label: '生活区' },
//   { value: 'game', label: '游戏区' },
//   { value: 'music', label: '音乐区' }
// ])
const categories = ref([])

const suggestedTags = ref([
  // 'Vlog', '教程', '测评', '科技前沿',
  // '数码', '开箱', '游戏解说', '生活记录'
])

onMounted(async()=>{
  const res = await getPartitionList()
  console.log(res)
  categories.value = res.data
  const res2 = await getTagList()
  suggestedTags.value = res2.data
})

// 禁用今天之前的日期
const disabledDate = (time) => {
  return time.getTime() < Date.now() - 24 * 3600 * 1000
}

// 表单提交
const formRef = ref(null)
const submitting = ref(false)

const submitForm = async () => {
  try {
    await formRef.value.validate()
    submitting.value = true

    const submitData = {
      ...form,
      videoTag: form.videoTag.join(','),
      videoCover: form.videoCover.replace(/^blob:/, '') // 处理预览地址
    }
    console.log('投稿数据:', submitData)
    const res = await uploadVideo(submitData)
    console.log(res)
    ElMessage.success('投稿成功！')
  } catch (error) {
    console.error('表单验证失败:', error)
  } finally {
    submitting.value = false
  }
}

// 模拟上传
const mockUpload = (file) => {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve(`mock-url/${file.name}`)
    }, 1500)
  })
}
// 新增上传触发方法
const videoUpload = ref(null)
const coverUpload = ref(null)

const triggerVideoUpload = () => {
  videoUpload.value?.$el.querySelector('.el-upload__input')?.click()
}

const triggerCoverUpload = () => {
  coverUpload.value?.$el.querySelector('.el-upload__input')?.click()
}
</script>

<style scoped>

.equal-height-row {
  display: flex;
  align-items: stretch; /* 确保列等高 */
}

.upload-page {
  padding: 30px;
  height: calc(100vh - 60px); /* 全屏高度 */
}

.upload-left {
  height: 100%;
  display: flex;
  flex-direction: column;
  gap: 30px;
}

.upload-section {
  flex: 1;
  background: #fff;
  border-radius: 8px;
  padding: 25px;
  box-shadow: 0 2px 12px rgba(0,0,0,0.1);
  display: flex;
  flex-direction: column;
}

.upload-core {
  flex: 1;
  margin-bottom: 15px;

  :deep(.el-upload-dragger) {
    height: 100%;
    display: flex;
    flex-direction: column;
    justify-content: center;
    border: 2px dashed #dcdfe6;
    transition: border-color 0.3s;

    &:hover {
      border-color: #409eff;
    }
  }
}

.video-upload {
  :deep(.el-upload-dragger) {
    min-height: 200px;
  }
}

.cover-upload {
  :deep(.el-upload-dragger) {
    aspect-ratio: 16/9;
    padding: 10px;
  }
}

.upload-content {
  text-align: center;

  .el-icon-upload {
    font-size: 50px;
    color: #909399;
    margin-bottom: 15px;
  }

  .upload-text {
    font-size: 14px;
    color: #606266;
  }
}

.cover-preview {
  width: 100%;
  height: 100%;

  .cover-image {
    width: 100%;
    height: 100%;
    object-fit: cover;
    border-radius: 4px;
  }

  .cover-placeholder {
    height: 100%;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    color: #8c939d;

    .el-icon-picture-outline {
      font-size: 40px;
      margin-bottom: 15px;
    }

    .cover-tip {
      font-size: 14px;
    }
  }
}

.upload-trigger-btn {
  width: 100%;
  height: 40px;
  margin-top: auto;

  i {
    margin-right: 8px;
  }
}

.upload-tip {
  font-size: 12px;
  color: #909399;
  text-align: center;
  margin-top: 10px;
}

.info-form {
  height: 100%;
  background: #fff;
  padding: 30px;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0,0,0,0.1);
}

.video-upload {
  :deep(.el-upload-dragger) {
    min-height: 100px;  /* 主要高度调整 */
    max-height: 0px;
    display: flex;
    align-items: center;
    justify-content: center;
  }
}

.upload-content {
  padding: 15px;  /* 增加内边距 */

  .el-icon-upload {
    font-size: 40px;
    margin-bottom: 10px;
    transition: all 0.3s;  /* 添加过渡效果 */
  }

  &:hover .el-icon-upload {
    color: #409eff;  /* 悬停变色 */
  }
}

.upload-text {
  line-height: 1.5;
}

/* 封面区域同步调整 */
.cover-upload {
  :deep(.el-upload-dragger) {
    min-height: 120px;

    .el-icon-picture-outline {
      font-size: 35px;  /* 原40px */
    }

    .cover-tip {
      font-size: 13px;  /* 原14px */
    }
  }
}
</style>